package net.zeus.redis;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;

import net.zeus.redis.util.JedisPoolUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Transaction;

public class JedisTest {

	
	private Jedis jedis;
	
	@Before
	public void doBefore() {
		System.out.println("connection ...");
		jedis = new Jedis("192.168.1.18", 6379);
		System.out.println("connection ok");
	}
	
	@Test
	public void redis1() {
		jedis.select(5);
		jedis.set("k10", "v10");
		
		System.out.println(jedis.get("k10"));
	}
	
	
	public void redisTx() {
		Transaction tx = jedis.multi();
		
		jedis.select(5);
		jedis.set("k11", "v11");
		
		// 提交事务
		tx.exec();
		
		// 放弃事务
//		tx.discard();
	}
	
	/**
	 * watch 乐观锁
	 * @return
	 */
	public boolean redisWatch() {
		long amt = 10L;
		jedis.watch("balance");
		
		long balance = Long.parseLong(jedis.get("balance"));
		
		if (balance < amt) {
			jedis.unwatch();
			return false;
		} else {
			Transaction tx = jedis.multi();
			
			// 余额减
			tx.decrBy("balance", amt);
			// 
			tx.incrBy("debt", amt);
			
			tx.exec();
			
			return true;
		}
	}
	
	@Test
	public void redisPool() {
		Jedis jedis = JedisPoolUtils.get();
		jedis.set("k1", "v1");
		JedisPoolUtils.release(jedis);
	}
	
	@Test
	public void redisCluster() {
		// redis cluster ip port
		Set<HostAndPort> jedisClusterNodes = new HashSet<>();
		jedisClusterNodes.add(new HostAndPort("127.0.0.1", 6379));
		jedisClusterNodes.add(new HostAndPort("127.0.0.1", 6380));
		
		// set config
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(100);
		config.setMaxIdle(10);
		config.setTestOnBorrow(true);
		
		// set cluster connection
		JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, 6000, 10, config);
		jedisCluster.set("k2", "v2");
		
		jedisCluster.get("k2");
		
		
		try {
			jedisCluster.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
